package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author ljh
 * @create 2020/12/23
 * @describe
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("X-User-Id");
        if(StringUtils.isEmpty(token)){
            try (PrintWriter writer = response.getWriter()) {
                response.setContentType("application/json; charset=utf-8");
            } catch (Exception e) {

            }
            return false;
        }
        UserContextHolder.getContext().set(token);
        log.info("token : [ {} ]", token);
        return true;
    }

}
